package com.example.music.service.serviceimpl;
import com.example.music.common.ServerResponse;
import com.example.music.domain.*;
import com.example.music.mapper.UserMapper;
import com.example.music.service.UserService;
import com.example.music.util.*;
import com.example.music.util.jwt.JwtUtil;
import com.example.music.util.redis.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Resource
    public RedisUtil redisUtil;

    private static String netPath= PropertiesUtils.getNetProperties();

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public List<Role> getRole() {
        return userMapper.getRole();
    }

    @Override
    public ServerResponse<String> register(User user) {
        //首先判断用户名是否存在
        User checkUsername=userMapper.checkUsername(user);
        if(ObjectUtils.isEmpty(checkUsername)){
            user.setCreateTime(new Date());
            User checkEmail=userMapper.checkEmail(user.getEmail());
            if(ObjectUtils.isEmpty(checkEmail)){
                user.setHeadPortrait("touxiang.jpg");
            }else{
                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
            }
            String checkCode = (String) redisUtil.get("musicemail_"+user.getEmail());
            if(StringUtils.isEmpty(checkCode)){
                return ServerResponse.createByErrorMsg("验证码已失效");
            }
            else if(!user.getCheckCode().equals(checkCode)){
                return ServerResponse.createByErrorMsg("验证码错误");
            }else{
                int i = userMapper.register(user);
                if (i != 0) {
                    redisUtil.del("musicemail_"+user.getEmail());
                    return ServerResponse.createBySuccessMsg("注册成功");
                } else {
                    return ServerResponse.createByErrorMsg("注册失败");
                }
            }
        }else{
            return ServerResponse.createByErrorMsg("该用户名已存在");
        }
    }




//    @Override
//    public ServerResponse<String> register(User user) {
//        String checkCode = (String) redisUtil.get("musicemail_"+user.getEmail());
//        if(StringUtils.isEmpty(checkCode)){
//            return ServerResponse.createByErrorMsg("验证码已失效");
//        }
//        else if(!user.getCheckCode().equals(checkCode)){
//            return ServerResponse.createByErrorMsg("验证码错误");
//        }else{
//            user.setCreateTime(new Date());
//            User checkEmail=userMapper.checkEmail(user.getEmail());
//            if(ObjectUtils.isEmpty(checkEmail)){
//                user.setHeadPortrait("touxiang.jpg");
//                User checkUsername=userMapper.checkUsername(user);
//                if(ObjectUtils.isEmpty(checkUsername)){
//                    int i = userMapper.register(user);
//                    if (i != 0) {
//                        redisUtil.del("musicemail_"+user.getEmail());
//                        return ServerResponse.createBySuccessMsg("注册成功");
//                    } else {
//                        return ServerResponse.createByErrorMsg("注册失败");
//                    }
//                }else{
//                    return ServerResponse.createByErrorMsg("该用户名已存在");
//                }
//            }else{
//                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
//            }
//        }
//    }


    /**
     * 邮箱验证
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this){
            //邮箱非空验证
            if(email==null||"".equals(email)){
                return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
            //调用邮箱发送
            AliyunMailUtil.sendMail(email,"浙江师范大学虚拟仿真实验项目用户注册","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时注册。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！感谢您的注册，祝您使用愉快！");
            redisUtil.set("musicemail_"+email,verificationCode,180);
            // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
            // todo 2019年8月28日09:23:18 接口中屏蔽验证码
            return ServerResponse.createBySuccessMsg("发送验证码成功");
        }
    }

    /**
     * 忘记密码时候，根据邮箱返回验证码
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        User resultCount = userMapper.checkEmail(email);
        if(ObjectUtils.isEmpty(resultCount)){
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //生成随机的验证码
        String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
        //调用邮箱发送
        AliyunMailUtil.sendMail(email,"浙江师范大学虚拟仿真实验项目用户重置密码","您的验证码为："+verificationCode+"。此验证码五分钟内有效，请及时重置密码。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！");
        //发送成功保存邮箱地址对应的验证码 todo 5分钟 已解决
        redisUtil.set("musicforget_"+email,verificationCode,300);
        return ServerResponse.createBySuccessMsg("验证码已经发送");
    }

    /**
     * 修改密码
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updatePassword(User user) {
        String checkCode = (String) redisUtil.get("musicforget_"+user.getEmail());
        int updatePasswordResult=0;
        if (StringUtils.isEmpty(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码已经失效");
        } else {
            if (!checkCode.equals(user.getCheckCode())) {
                return ServerResponse.createByErrorMsg("验证码输入错误");
            } else {
                User checkEmailUser = userMapper.checkEmail(user.getEmail());
                if (!ObjectUtils.isEmpty(checkEmailUser)) {
                    updatePasswordResult = userMapper.updatePassword(user);
                }
            }
        }
        if (updatePasswordResult != 0) {
            redisUtil.del("musicforget_"+user.getEmail());
            return ServerResponse.createBySuccessMsg("修改成功");
        } else {
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }


    @Override
    public void expertLogin(User expertLoginUser) {
        userMapper.expertLogin(expertLoginUser);
    }

    @Override
    public ServerResponse<PageInfo> searchUser(Integer pageNum, Integer pageSize, String username) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.searchUser(username);
        PageInfo pageInfo = new PageInfo(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Transactional
    @Override
    public ServerResponse deleteUser(Integer id) {
        userMapper.delSelfSong(id);//删除用户之前先把用户上传的伴奏删除
        int deleteStatus = userMapper.deleteUser(id);
        if (deleteStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功删除该学生");
        } else {
            return ServerResponse.createByErrorMsg("删除该学生失败");
        }
    }

    @Transactional
    @Override
    public ServerResponse uploadSong(Song song,List<Lyrics> lyricsList) {
        int uploadSongStatus=userMapper.uploadSong(song);
        lyricsList.forEach(lyrics -> {
            lyrics.setSongId(song.getSongId());
        });
        int status=userMapper.uploadLyric(lyricsList);

        if(status!=0){
            return ServerResponse.createBySuccess("成功上传歌曲信息");
        }else{
            return ServerResponse.createByErrorMsg("上传歌曲信息失败");
        }
    }

    @Override
    public ServerResponse getSong(User user, JSONObject jsonObject) {
        Integer pageNum=1;
        Integer pageSize=10;
        String keyword=jsonObject.getString("keyword");
        if(jsonObject.length()!=0){
           pageNum=jsonObject.getInt("pageNum");
           pageSize=jsonObject.getInt("pageSize");
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Song> songList=userMapper.getSong(user.getId(),user.getRoleId(),keyword);
        for (Song song : songList) {
            song.setMusic(netPath+song.getMusic());
            song.setSongVoice(netPath+song.getSongVoice());
            song.setSongAccompany(netPath+song.getSongAccompany());
            song.setSongPicture(netPath+song.getSongPicture());
            song.setSongOriginal(netPath+song.getSongOriginal());
        }
        PageInfo pageInfo=new PageInfo(songList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse getSongById(Integer songId) {
        Song song=userMapper.getSongById(songId);
        song.setSongPicture(netPath+song.getSongPicture());
        song.setSongOriginal(netPath+song.getSongOriginal());
        song.setSongAccompany(netPath+song.getSongAccompany());
        return ServerResponse.createBySuccess(song);
    }

    @Override
    public ServerResponse getSongByKind(Integer kindId, Integer pageNum, Integer pageSize,String keyword,User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<Song> songList=userMapper.getSongByKind(kindId,keyword,user.getId());
        songList.forEach(song -> {
            song.setSongAccompany(netPath+song.getSongAccompany());
            song.setSongOriginal(netPath+song.getSongOriginal());
            song.setSongPicture(netPath+song.getSongPicture());
        });
        PageInfo pageInfo=new PageInfo(songList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getSongKind() {
        List<SongKind> songKindList=userMapper.getSongKind();
        return ServerResponse.createBySuccess(songKindList);
    }

    @Override
    public U3DSong getU3dSongInfo(Integer songId) {
        U3DSong u3DSong=userMapper.getU3dSongInfo(songId);
        return u3DSong;
    }

    @Override
    public ServerResponse updateHeadPortrait(Integer id, String headPortrait,User user) {
        int updateHeadPortraitStatus=userMapper.updateHeadPortrait(id,headPortrait);
        if(updateHeadPortraitStatus!=0){
            User loginUser =userMapper.checkUsername(user);
//            loginUser.setLoginTime(System.currentTimeMillis());
            loginUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);//置空密码
            loginUser.setHeadPortrait(netPath+loginUser.getHeadPortrait());
            // todo important token有效期10个小时
            String token = JwtUtil.sign(loginUser,600000L*1000L*6L);//token有效期10小时
            return ServerResponse.createBySuccess(token);
        }else{

            return ServerResponse.createByErrorMsg("修改失败");
        }
    }


    @Override
    public ServerResponse getU3dByValue(Integer songId, String path, User u) {
        Report report=new Report();
        report.setReportName(u.getUsername());
        report.setSelfSinging(path);
        report.setReportUserId(u.getId());
        Song song=userMapper.getSongById(songId);
        String songAccompany=song.getSongAccompany();
        try{
            String selfSinging= CmdUtil.mergeMp3(songAccompany,path);
            report.setReportMusicName(song.getSongName());
            report.setOriginSongId(songId);
            report.setSelfSinging(selfSinging);
            int insertReportStatus=userMapper.insertReport(report);
            if(insertReportStatus!=0){
                U3DReport u3DReport=new U3DReport();
                u3DReport.setReportId(report.getReportId());
                u3DReport.setSongOriginal(netPath+selfSinging);
                return ServerResponse.createBySuccess(u3DReport);
            }else{
                return ServerResponse.createByErrorMsg("音乐合成失败");
            }
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("音乐合成失败");
        }

    }



//    @Override
//    public ServerResponse getU3dByValue(Integer songId, User u,String selfSinging) {
//        Report report=new Report();
//        report.setReportName(u.getUsername());
//        report.setSelfSinging(selfSinging);
//        report.setReportUserId(u.getId());
//        Song song=userMapper.getSongById(songId);
////        String songAccompany=song.getSongAccompany();
//        try{
////           String selfSinging= CmdUtil.mergeMp3(songAccompany,path);
//            report.setReportMusicName(song.getSongName());
//            report.setOriginSongId(songId);
//            report.setSelfSinging(selfSinging);
//            int insertReportStatus=userMapper.insertReport(report);
//            if(insertReportStatus!=0){
//                U3DReport u3DReport=new U3DReport();
//                u3DReport.setReportId(report.getReportId());
//                u3DReport.setSongOriginal(netPath+selfSinging);
//                return ServerResponse.createBySuccess(u3DReport);
//            }else{
//                return ServerResponse.createByErrorMsg("音乐合成失败");
//            }
//        }catch (Exception e){
//            return ServerResponse.createByErrorMsg("音乐合成失败");
//        }
//
//    }



    @Override
    public ServerResponse getUserReportSong(Integer id,Integer pageNum,Integer pageSize,String keyword) {
        PageHelper.startPage(pageNum,pageSize);
        List<ReportResult> reportList=userMapper.getUserReportSong(id,keyword);
        reportList.forEach(reportResult -> {
            reportResult.setSelfSinging(netPath+reportResult.getSelfSinging());
            reportResult.setSongPicture(netPath+reportResult.getSongPicture());
        });
        PageInfo pageInfo=new PageInfo(reportList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse delUserReportSong(Integer reportId) {
        String reportSongPath=userMapper.getReportSongPath(reportId);
        FileUploadAndDownload fileUploadAndDownload=new FileUploadAndDownload();
        fileUploadAndDownload.deleteSongFile(reportSongPath);
        long delUserReportSong=userMapper.delUserReportSong(reportId);
        if(delUserReportSong!=0){
            return ServerResponse.createBySuccess("成功删除该歌曲");
        }else {
            return ServerResponse.createByErrorMsg("删除该歌曲失败");
        }
    }

    @Override
    public String downloadReportSong(Integer reportId) {
        return userMapper.downloadReportSong(reportId);
    }

    @Override
    public ServerResponse changePublicity(Integer reportId, boolean publicity) {
        long  changePublicityStatus=userMapper.changePublicity(reportId,publicity);
        if(changePublicityStatus!=0){
            return ServerResponse.createBySuccess("操作成功");
        }else{
            return ServerResponse.createByErrorMsg("操作失败");
        }
    }

    @Override
    public String downloadOriginSong(Integer songId) {
        return userMapper.downloadOriginSong(songId);
    }

    @Override
    public ServerResponse getReportDynamic(Integer pageNum, Integer pageSize, String keyword,Integer uid,Integer roleId) {
        PageHelper.startPage(pageNum,pageSize);
        List<ReportDynamic> reportDynamicList=new ArrayList<>();
        if(roleId==4) {
            reportDynamicList = userMapper.getReportDynamicPsyh(keyword, uid);
        }else {
            reportDynamicList = userMapper.getReportDynamic(keyword, uid);
        }

        reportDynamicList.forEach(reportDynamic -> {
            reportDynamic.setHeadPortrait(netPath+reportDynamic.getHeadPortrait());
            reportDynamic.setSelfSinging(netPath+reportDynamic.getSelfSinging());
            reportDynamic.setSongPicture(netPath+reportDynamic.getSongPicture());
        });
        PageInfo pageInfo=new PageInfo(reportDynamicList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse u3dInsertReport(Report report) {
        int u3dInsertReportStatus=userMapper.u3dInsertReport(report);
        if(u3dInsertReportStatus!=0){
            return ServerResponse.createBySuccess("上传成绩成功");
        }else{
            return ServerResponse.createByErrorMsg("上传成绩失败");
        }
    }

    @Override
    public ServerResponse delSong(Integer songId) {
        Song song=userMapper.getSongById(songId);
//        FileUploadAndDownload fileUploadAndDownload=new FileUploadAndDownload();
//        fileUploadAndDownload.deleteSongFile(song.getSongAccompany());
        int delSongStatus=userMapper.delSong(songId);
        if(delSongStatus!=0){
            return ServerResponse.createBySuccess("成功删除该伴奏");
        }else{
            return ServerResponse.createByErrorMsg("删除该伴奏失败");
        }
    }

    @Override
    public ServerResponse getIndexSong() {
        Song song=userMapper.getIndexSong();
        song.setSongAccompany(netPath+song.getSongAccompany());
        song.setSongPicture(netPath+song.getSongPicture());
        song.setSongOriginal(netPath+song.getSongOriginal());
        return ServerResponse.createBySuccess(song);
    }

    @Override
    public ServerResponse getExperimentReport(User user,Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum,pageSize);
        List<ExperimentReport> experimentReportList=userMapper.getExperimentReport(keyword,user.getRoleId(),user.getId());
        experimentReportList.forEach(experimentReport -> {
            experimentReport.setSelfSinging(netPath+experimentReport.getSelfSinging());
        });
        PageInfo pageInfo=new PageInfo(experimentReportList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Transactional
    @Override
    public ServerResponse updateSong(Song song,List<Lyrics> lyricsList) {
        Integer updateSongStatus=userMapper.updateSong(song);
        if(updateSongStatus!=0){
            if(!StringUtils.isEmpty(song.getSongName())){
                userMapper.updateMusicName(song.getSongName(),song.getSongId());
            }
            if(lyricsList.size()!=0){
                userMapper.deleteLyrics(song.getSongId());
                userMapper.uploadLyric(lyricsList);
            }
            return ServerResponse.createBySuccess("修改伴奏信息成功！");
        }else{
            return ServerResponse.createByErrorMsg("修改伴奏信息失败！");
        }
    }

    @Override
    public User loginUser(User u) {
        return userMapper.loginUser(u);
    }

    @Override
    public Integer uploadLyric(List<Lyrics> lyricsList) {
        return userMapper.uploadLyric(lyricsList);
    }

    @Override
    public List<U3DLyrics> getLyrics(Integer songId) {
        return userMapper.getLyrics(songId);
    }

    @Override
    public ServerResponse adminComment(ExperimentReport experimentReport) {
        if(!StringUtils.isEmpty(experimentReport.getAdminComment())||!StringUtils.isEmpty(experimentReport.getReportScore())){
            experimentReport.setStatus(true);
        }
        Integer adminCommentStatus=userMapper.adminComment(experimentReport);
        if(adminCommentStatus!=0){
            return ServerResponse.createBySuccessMsg("评论成功");
        }else{
            return ServerResponse.createByErrorMsg("评论失败");
        }
    }
}
